package com.defysoft.waukids.main;

import java.io.IOException;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.widget.ImageView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.BasicInfo;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.defysoft.waukids.main.Main_MainFrame.BackPressCloseHandler;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Main_Intro extends BaseActivity {

	ImageView logo;
	ImageView waukidslogo;
	private GoogleCloudMessaging gcm; // gcm uuid 얻기 위해 선언한 메소드들에 사용.
	String regId = null; // uuid담을 변수.
	PublicSharedpreferences psf;
	SharedPreferences.Editor editor;
	Data_Sharedpreferences.SF_Member member;
	Sqlite_Connect sc;
	Cursor cursor;
	String GO_MESSAGE, PK_Mes_Code, Mes_Category;
	// 이미지 세팅
		DisplayImageOptions options;
		ImageLoader imageLoader;
		Data_Sharedpreferences.SF_School school_data;	
	private final int UPDATE_VERSION = 7;
	private final int FAIR_VERSION = 6;
	private final int CHECK_ID = 5;
	private final int START_MAIN = 8;
	private final int START_LOGIN = 9;
	private final int FAIL_ADD_LOG = 3;
	private final int SUCCESS_ADD_LOG = 4;
	private final int FAIL_CONNECT =2;
	private final int LOGIN_CHECK = 10; // 저장된 정보있는지 검사흐름 (boolean
										// autologin으로구분)

	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.main_intro_activity);
		setImgSetting();
		setStartData();
		startNetwork(1);
	}

	public void setImgSetting() {
		// 이미지 세팅.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
		imageLoader = ImageLoader.getInstance();

		options = new DisplayImageOptions.Builder().cacheInMemory(true)
		/* .imageScaleType(ImageScaleType.EXACTLY) */
		.cacheOnDisc(true).considerExifParams(true).build();
	}
	
	@Override
	public void setStartData() {
		super.setStartData();
		GO_MESSAGE = getIntent().getStringExtra("GO_MESSAGE");
		PK_Mes_Code = getIntent().getStringExtra("PK_Mes_Code");
		Mes_Category = getIntent().getStringExtra("Mes_Category");
		sc = new Sqlite_Connect(this);
		psf = new PublicSharedpreferences(this);
		editor = psf.getMember_edit();
		psf.setMembersp();
		member = psf.getMembersp();
		
		psf.setSchoolsp();
		school_data = psf.getSchoolsp();
		
		psf.delClasssp();
		psf.delStudentsp();
		
		logo = (ImageView) findViewById(R.id.MAIN_INTRO_LOGO);
		waukidslogo = (ImageView) findViewById(R.id.MAIN_INTRO_WAUKIDSLOGO);
		
		if(school_data.Logo.equals("")){
			logo.setImageResource(R.drawable.icon);
		}else{
			imageLoader.displayImage(HTTP_URL_LOGOPHOTO+school_data.Logo, logo,options);
		}
		//sql test
		cursor =sc.check_Err_Log();
		if(cursor.getCount()>0){
			startNetwork(3);
		}
	}

	private String getVersion() { // 입력되는 버전값.
		PackageInfo pi = null;
		try {
			pi = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return pi.versionName;
	}

	public void check_Login() {
		if (checkPlayServices()) {
			registerInBackground(); // uuid생성. 후 LOGIN_CHECK
		} else {
			regId = ""; // uuid 없이.
			Toast.makeText(this, "구글 푸시서비스 사용불가능", Toast.LENGTH_LONG).show();
			sendMessage(LOGIN_CHECK);
		}
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case LOGIN_CHECK: // 저장된 정보있는지 검사흐름
			if (member.Email == "" || member.Email == null || member.Pass == ""
					|| member.Pass == null) {

				sendMessage(START_LOGIN);

			} else {
				startNetwork(2);
			}
			break;
		case START_LOGIN:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Intent loginintent = new Intent(this, Main_Login.class);
			loginintent.putExtra("MEM_UUID", regId);
			endDIal();
			startActivity(loginintent);
			finish();
			break;
		case START_MAIN:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Intent mainintent = new Intent(this, Main_MainFrame.class).putExtra("GO_MESSAGE", GO_MESSAGE);
			startActivity(mainintent);
			finish();
			break;
		case FAIR_VERSION: // 버전 얻어오는데 실패
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, "버전 정보를 얻는데 실패했습니다.", Toast.LENGTH_LONG)
					.show();
			break;
		case CHECK_ID:
			check_Login();
			break;
		case UPDATE_VERSION: // 저장된 정보있는지 검사흐름
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			AlertDialog alert;
			AlertDialog.Builder builder = new AlertDialog.Builder(
					Main_Intro.this);
			builder.setMessage("버전이 바뀌었습니다 구글 스토어에서 업데이트해주세요")
					.setCancelable(false)
					.setPositiveButton("업데이트",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									try {
										startActivity(new Intent(
												Intent.ACTION_VIEW,
												Uri.parse("market://details?id="
														+ getPackageName())));
									} catch (android.content.ActivityNotFoundException anfe) {
										startActivity(new Intent(
												Intent.ACTION_VIEW,
												Uri.parse("http://play.google.com/store/apps/details?id="
														+ getPackageName())));
									}
								}
							})
					.setNegativeButton("종료",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
									finish();
								}
							});
			alert = builder.create();
			alert.show();
			break;
			
		case CATCH_EXCEPTION:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			sc.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Main_Intro", member.Email);
			break;
			
		case SUCCESS_ADD_LOG:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			sc.delete_Err_Log();
			break;
		
		case FAIL_ADD_LOG:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			break;
		
		case FAIL_CONNECT:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			sc.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"MAIN_MAIN_FRAME", member.Email);
			break;
		}
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case 1:
					if (checkVersion()) {
						onNetworkCallback(CHECK_ID, "");
					}
					break;
				case 2:
					check_Login_Thread();
					break;
				
				case 3: 
					getError();
					break;
				}
			}
		});
		firstThread.start();

	}

	public void getError(){
		String test="";
		while (cursor.moveToNext()) {
			test=cursor.getString(0)+"//"+cursor.getString(1)+"//"+cursor.getInt(2)+"//"+cursor.getString(3)+"//"+cursor.getString(4);

		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_ERROR_LOG + "&error_log="
							+ test));
			if (jsonObject.getBoolean("success")) {
			
				onNetworkCallback(SUCCESS_ADD_LOG, "");
			} else {
				onNetworkCallback(FAIL_ADD_LOG, "");
			}
		} catch (Exception e) {
			onNetworkCallback(FAIL_CONNECT, e.toString()+" where getError()");
		}
}
	}
	
	public void check_Login_Thread() {
		String memberjson = "";
		String schooljson = "";
		JSONObject memberJsonObject ;
		JSONObject schoolJsonObject;
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_MAIN_LOGIN + "&email=" + member.Email
							+ "&pass=" + member.Pass + "&uuid=" + regId));
			if (jsonObject.getBoolean("success")) {
				memberjson = jsonObject.getString("payload");
				schooljson = jsonObject.getString("sch");
					memberJsonObject = new JSONObject(memberjson);
					schoolJsonObject = new JSONObject(schooljson);
					if (!memberJsonObject.getString("Mem_Connect").equals("0")) {
					editor = psf.getMember_edit();
					editor.putString(
							PublicSharedpreferences.SF_Member_Key.EMAIL,
							memberJsonObject.getString("PK_Mem_Email"));
					editor.putString(
							PublicSharedpreferences.SF_Member_Key.CLASS,
							memberJsonObject.getString("FK_Cla_Mem_Code"));
					editor.putString(
							PublicSharedpreferences.SF_Member_Key.CONNECT,
							memberJsonObject.getString("Mem_Connect"));
					editor.putString(
							PublicSharedpreferences.SF_Member_Key.CREATEDATE,
							memberJsonObject.getString("Mem_CreateDate"));
					editor.putString(
							PublicSharedpreferences.SF_Member_Key.NAME,
							memberJsonObject.getString("Mem_Name"));
					editor.putString(
							PublicSharedpreferences.SF_Member_Key.Rank,
							memberJsonObject.getString("Mem_Rank"));
					editor.putString(
							PublicSharedpreferences.SF_Member_Key.SCHOOL,
							memberJsonObject.getString("FK_Sch_Mem_Code"));
					editor.putString(
							PublicSharedpreferences.SF_Member_Key.UUID,
							memberJsonObject.getString("Mem_Uuid"));
					editor.commit();

					editor = psf.getSchool_edit();
					editor.putString(
							PublicSharedpreferences.SF_School_Key.ADDRESS,
							schoolJsonObject.getString("Sch_Add"));
					editor.putString(
							PublicSharedpreferences.SF_School_Key.ADDRESS_Code,
							schoolJsonObject.getString("FK_Add_Sch_Code"));
					editor.putString(
							PublicSharedpreferences.SF_School_Key.CODE,
							schoolJsonObject.getString("PK_Sch_Code"));
					editor.putString(
							PublicSharedpreferences.SF_School_Key.DELETE,
							schoolJsonObject.getString("IsDelete"));
					editor.putString(
							PublicSharedpreferences.SF_School_Key.INFO,
							schoolJsonObject.getString("Sch_Info"));
					editor.putString(
							PublicSharedpreferences.SF_School_Key.LOGO,
							schoolJsonObject.getString("Sch_Logo"));
					editor.putString(
							PublicSharedpreferences.SF_School_Key.NAME,
							schoolJsonObject.getString("Sch_Name"));
					editor.putString(
							PublicSharedpreferences.SF_School_Key.DOCUMENT,
							schoolJsonObject.getString("Sch_Document"));
					editor.putString(
							PublicSharedpreferences.SF_School_Key.CCTV,
							schoolJsonObject.getString("Sch_Cctv"));
					editor.putString(
							PublicSharedpreferences.SF_School_Key.CCTVTIMESTART,
							schoolJsonObject.getString("Sch_Cctv_Time_Start"));
					editor.putString(
							PublicSharedpreferences.SF_School_Key.CCTVTIMESTOP,
							schoolJsonObject.getString("Sch_Cctv_Time_Stop"));
					editor.commit();

				
					onNetworkCallback(START_MAIN, "");
				}else {
					onNetworkCallback(START_LOGIN, "");
				}
			} else {
				onNetworkCallback(START_LOGIN, "");
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString() +" where check_Login_Thread()");
		}
		;
	}

	private boolean checkVersion() {

		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					"http://waukids.com/wau/getversion.php", ""));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				msg = new JSONObject(msg).getString("Waukids");
				msg = msg.replace("d", ".");
				if (Double.parseDouble(msg) > Double.parseDouble(getVersion())) { // 학원정보저장.
					onNetworkCallback(UPDATE_VERSION, "");
					return false;
				} else {
					return true;
				}

			} else {
				onNetworkCallback(FAIR_VERSION, "");
				return false;
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString() +" where checkVersion()");
		}
		;
		return false;
	}

	// gcm uuid 얻기 위해 선언한 메소드들
	private void registerInBackground() {
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String msg = "";
				try {
					if (gcm == null) {
						gcm = GoogleCloudMessaging
								.getInstance(getApplicationContext());
					}
					regId = gcm.register(BasicInfo.PROJECT_ID);
					msg = "Device registered, registration ID=" + regId;

					storeRegistrationId(regId);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();

				}
				return msg;
			}

			@Override
			protected void onPostExecute(String msg) {
				sendMessage(LOGIN_CHECK);
			}
		}.execute(null, null, null);
	}

	private void storeRegistrationId(String regId) {
		int appVersion = getAppVersion();
		BasicInfo.resid = regId;
		BasicInfo.appversion = appVersion;
	}

	// 버전체크
	private int getAppVersion() {
		try {
			PackageInfo packageInfo = getPackageManager().getPackageInfo(
					getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this, 9000)
						.show();
			} else {
				finish();
			}
			return false;
		}
		return true;
	}
}
